import sys, os
base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_path)

import base64
import pika
from pika import channel
from redis import StrictRedis
from pika import PlainCredentials
from pika.connection import Connection
import json
from tools.images.wordcloud import WordCloudGenerator
from tools.images.watermark import WaterMark
from tools.images.ocr import OCRModel
import re
from tools.spider import const
from tools.spider.mail import MsgGenerator, Sender
from tools.document.pdfCut import splitPdf
from tools.document.pdfWatermark import add_watermark

IMAGE_PREFIX = 'pytools:image:'
DOCUMENT_PREFIX = 'pytools:document:'

# redis缓存
redis_client: StrictRedis = StrictRedis(host='1.15.170.222', port='6379')

# RabbitMQ的链接认证
auth: PlainCredentials = PlainCredentials(username='guest', password='guest')

connet_parameter: pika.ConnectionParameters = pika.ConnectionParameters(
    host='1.15.170.222', port='5672', virtual_host='/', credentials=auth)
connection: Connection = pika.BlockingConnection(connet_parameter)
channel = connection.channel()


def wordcloud_callback(ch, method, properties, body):
    """词云消费者"""
    try:
        data = json.loads(body)
        sentence = data.get('word')  # 语句
        color = data.get('color')  # 颜色
        image = data.get('image')  # 图片base64
        identifier = data.get('identifier')  # 标识符
        raw = re.sub('^data:image/.+;base64,', '', image)  # 真实base64
        generator = WordCloudGenerator(sentence=sentence,
                                       color=color,
                                       source=base64.b64decode(raw))
        wordcloud = generator.create_cloud()
        result = base64.b64encode(wordcloud.getvalue()).decode('utf-8')
        redis_client.setex(IMAGE_PREFIX + identifier, 20000, result)
    except Exception as e:
        print(e)


def watermarker_callback(ch, method, properties, body):
    try:
        """水印消费者"""
        data = json.loads(body)
        image = data.get('image')  # 图片base64
        identifier = data.get('identifier')  # 标识符
        raw = re.sub('^data:image/.+;base64,', '', image)  # 真实base64
        marker = WaterMark(source=base64.b64decode(raw), **data)
        out = marker.water_mark()
        result = base64.b64encode(out.getvalue()).decode('utf-8')
        redis_client.setex(IMAGE_PREFIX + identifier, 20000, result)
    except Exception as e:
        print(e)


def ocr_callback(ch, method, properties, body):
    try:
        """OCR消费者"""
        data = json.loads(body)
        image = data.get('image')  # 图片base64
        identifier = data.get('identifier')  # 标识符
        raw = re.sub('^data:image/.+;base64,', '', image)  # 真实base64
        model = OCRModel(source=base64.b64decode(raw), **data)
        result = model.readtext()
        redis_client.setex(IMAGE_PREFIX + identifier, 20000, json.dumps(result))
    except Exception as e:
        print(e)


def pdfcut_callback(ch, method, properties, body):
    try:
        """pdf剪切消费者"""
        data = json.loads(body)
        pdf = data.get('source')  # 文件的base64
        identifier = data.get('identifier')  # 标识符
        print('pdfcut值守:' + identifier)
        startPage = data.get('startPage')
        endPage = data.get('endPage')
        raw = re.sub('^data:application/pdf;base64,', '', pdf)  # 真实base64
        out = splitPdf(base64.b64decode(raw), startPage, endPage) # 获取剪切结果
        result = base64.b64encode(out.getvalue()).decode('utf-8')
        redis_client.setex(DOCUMENT_PREFIX + identifier, 20000, json.dumps(result))
    except Exception as e:
        print(e)

def pdfwatermarker_callback(ch, method, properties, body):
    try:
        """pdf水印消费者"""
        data = json.loads(body)
        marked = data.get('marked')  # 文件的base64
        marker = data.get('marker')
        identifier = data.get('identifier')  # 标识符
        print('pdfwatermarker值守:' + identifier)
        marked_raw = re.sub('^data:application/pdf;base64,', '', marked)  # 真实base64
        marker_raw = re.sub('^data:application/pdf;base64,', '', marker)
        out = add_watermark(base64.b64decode(marked_raw), base64.b64decode(marker_raw))
        result = base64.b64encode(out.getvalue()).decode('utf-8')
        redis_client.setex(DOCUMENT_PREFIX + identifier, 20000, json.dumps(result))
    except Exception as e:
        print(e)



HOT_INFO_PREFIX = 'pytools:info:'

# 邮箱发送消费者
def send_email(ch, method, properties, body):
    data = json.loads(body)
    kind = data.get('kind')
    email = data.get('email')
    result = redis_client.get(HOT_INFO_PREFIX + kind)
    if result is not None:
        result = json.loads(result)
    generator = MsgGenerator(kind, const.FROM_EMAIL_NAME, const.FROM_EMAIL, email)
    msg = generator.plain_msg(json.dumps(result))
    sender = Sender(const.SMTP_SERVER, const.SMTP_PORT, const.FROM_EMAIL, email, const.SMTP_PASSWORD)
    sender.send_mail(msg)
    print('邮件发送成功: ' +  email)
    

channel.basic_consume(queue='pytools.image.wordcloud',
                      on_message_callback=wordcloud_callback,
                      auto_ack=True)

channel.basic_consume(queue='pytools.image.watermarker',
                      on_message_callback=watermarker_callback,
                      auto_ack=True)

channel.basic_consume(queue='pytools.image.ocr',
                      on_message_callback=ocr_callback,
                      auto_ack=True)

channel.basic_consume(queue='pytools.pdf.cut',
                      on_message_callback=pdfcut_callback,
                      auto_ack=True)

channel.basic_consume(queue='pytools.pdf.watermark',
                      on_message_callback=pdfwatermarker_callback,
                      auto_ack=True)


channel.basic_consume(queue='pytools.email.queue',
                      on_message_callback=send_email,
                      auto_ack=True)

channel.start_consuming()
